package top.jimc.ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import top.jimc.ssm.common.base.controller.BaseController;
import top.jimc.ssm.po.User;
import top.jimc.ssm.service.UserService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Jimc.
 * @since 2018/10/12.
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("listPage")
    public ModelAndView listPage() {
        ModelAndView mv = new ModelAndView("user/list");
        mv.addObject("users", userService.selectAll());
        return mv;
    }

    @GetMapping("addPage")
    public ModelAndView addPage() {
        return new ModelAndView("user/add");
    }

    @PostMapping("add")
    @ResponseBody
    public Map<String, Object> add(User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            userService.insertSelective(user);
            result.put("success", true);
            result.put("msg", "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "添加失败");
        }
        return result;
    }

    @GetMapping("updatePage")
    public ModelAndView updatePage(Integer userId) {
        ModelAndView mv = new ModelAndView("user/update");
        mv.addObject("user", userService.selectByKey(userId));
        return mv;
    }

    @PostMapping("update")
    @ResponseBody
    public Map<String, Object> update(User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            userService.updateAll(user);
            result.put("success", true);
            result.put("msg", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "修改失败");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    public Map<String, Object> delete(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            userService.delete(userId);
            result.put("success", true);
            result.put("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "删除失败");
        }
        return result;
    }
}
